// (C) Copyright 2009, 2010 Communications Programming, Inc.
/***************************************************************************************************************
*  Name: handle.c
*
*  Description: Functions to allocate and maintain i/o handles
*
*  INT16 handleNumberGet( DevInfo *devInfoBlk );		// stores the devInfoBlk address in the next available
*													// (non-null) handle slot 
*  Returns the slot number for use as the i/o handle, or -1 if none available
*   
*  DevInfo * handleDevInfoGet( INT16 handle );		// handle returned from handleNumberGet()
*
*  Returns the address of the DevInfo device information blk for a given handle, or NULL if handle not open
*	
*  void handleNumberClose( INT16 handle );	 		// handle returned from handleNumberGet()
*
*  Sets the handle slot to Null, making it available for handleNumberGet() new allocation
*
*  Revision History:
*  Date    Who  Comments
*  ------  ---  -----------------------------------------------------------------------------------------
*  100928  RLP	Created.
*
***************************************************************************************************************/
#include <p32xxxx.h>
#include <userLib.h>
#include <stddef.h>

#define MAX_HANDLE 20 			// tables should contain one more NULL than this, followed by -1

static DevInfo * handleTable[MAX_HANDLE+2] = {	NULL, NULL, NULL, NULL, NULL, \
												NULL, NULL, NULL, NULL, NULL, \
												NULL, NULL, NULL, NULL, NULL, \
												NULL, NULL, NULL, NULL, NULL, NULL, (DevInfo *)-1 };

INT16 handleNumberGet( DevInfo *devInfoPtr )		// stores the devInfoBlk address in the next available
{
	int i;

	for( i = 1; handleTable[i] != (DevInfo *)-1; ++i )
	{
		if( handleTable[i] == NULL )
		{
			handleTable[i] = devInfoPtr;
			return(i);							// valid handle
		}
	}
	return(-1);									// out of handles
}

DevInfo * handleDevInfoGet( INT16 handle )		// handle returned from handleNumberGet()
{
	if( (handle < 1) || (handle > MAX_HANDLE) )
		return( NULL );
	return( handleTable[handle] );
}

void handleNumberClose( INT16 handle )	 		// handle returned from handleNumberGet()
{
	if( (handle < 1) || (handle > MAX_HANDLE) )
		return;
	handleTable[handle] = NULL;
}
